//
//  M4KFAlertView.swift
//  M4
//
//  Created by YuChuang on 2024/8/9.
//

import UIKit

class M4KFAlertView: UIView {
    var didTapKFzxHandle: (() -> Void)?

    lazy var bgView: UIView = {
        let bg = UIView()
        bg.backgroundColor = .white
        bg.layer.cornerRadius = 2
        return bg
    }()
    
    lazy var closeButton: UIButton = {
        let close = UIButton(type: .custom)
        close.setTitle("", for: .normal)
        close.setImage(UIImage(named: "icon_close"), for: .normal)
        close.addTarget(self, action: #selector(m4CloseAlert), for: .touchUpInside)
        return close
    }()
    
    lazy var imageView: UIImageView = {
        let img = UIImageView()
        img.image = UIImage(named: "pop_icon_phone")
        return img
    }()
    
    lazy var tipLabel: UILabel = {
        let label = UILabel()
        label.text = "Teléfono de atención al cliente oficial o WhatsApp"
        label.numberOfLines = 0
        label.textColor = COLOR_333333
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        return label
    }()
    
    lazy var SoporteButton: UIButton = {
        let close = UIButton(type: .custom)
        close.setTitle("Soporte en línea >", for: .normal)
        close.layer.cornerRadius = 20
        close.layer.masksToBounds = true
        close.setTitleColor(UIColor.init(hex: 0x00479D), for: .normal)
        close.backgroundColor = UIColor.init(hex: 0xEBF4FF)
        close.addTarget(self, action: #selector(m4SoporteBut), for: .touchUpInside)
        return close
    }()

    override init(frame: CGRect) {//28
        super.init(frame: .zero)
        self.frame = CGRect(x: 0, y: 0, width: M4ScreenWidth, height: M4ScreenHeight)
        self.tag = 1111
        self.backgroundColor = COLOR_000000.withAlphaComponent(0.6)
        self.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-30)
            make.centerY.equalToSuperview().offset(-28)
        }
        self.addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.width.height.equalTo(26)
            make.top.equalTo(bgView.snp.bottom).offset(30)
            make.centerX.equalToSuperview()
        }
        bgView.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(30)
            make.width.height.equalTo(70)
            make.centerX.equalToSuperview()
        }
        bgView.addSubview(tipLabel)
        tipLabel.snp.makeConstraints { make in
            make.top.equalTo(imageView.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.centerX.equalToSuperview()
        }
        let phoneArray = M4ConfigDataManager.m4ConfigShare.m4servicePhone.components(separatedBy: ",")
        for i in 0..<phoneArray.count {
            let item = M4KFItemView()
            item.numberLabel.text = phoneArray[i]
            bgView.addSubview(item)
            item.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(35)
                make.right.equalToSuperview().offset(-35)
                make.top.equalTo(tipLabel.snp.bottom).offset(20+(28+30)*i)
                make.height.equalTo(28)
                if i == phoneArray.count-1 {
                    make.bottom.equalToSuperview().offset(-100)
                }
            }
        }
        
        bgView.addSubview(SoporteButton)
        SoporteButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(35)
            make.right.equalToSuperview().offset(-35)
            make.bottom.equalToSuperview().offset(-30)
            make.height.equalTo(40)

        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    @objc private func m4SoporteBut() {
        didTapKFzxHandle?()
        self.M4AlertViewHidden()
        
        
        if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
            let topVC = rootVC.M4showTopViewController()
            let VC = M4KeFuViewController()
            let baseURL = M4NetworkAPI.zxkfPath.rawValue
            let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
            let params: [String: String] = [
                            "jtrssss": M4UserDataManager.m4UserShare.M4appUserId,
                            "htysjzdrrr": M4UserDataManager.m4UserShare.M4userName,
                            "jahafcgg": M4UserDataManager.m4UserShare.M4UserMobile,
                            "jrfdfdaaba": M4UserDataManager.m4UserShare.adjustAdid,
                            "sdjs": "iOS",
                            "jrss": version ?? ""
                        ]


                        let parmssss = params.map { "\($0.key)=\($0.value)" }.joined(separator: "&")
                        let m4String1 = "\(baseURL)?\(parmssss)"
            
            
            VC.M4urlStr = m4String1
            
            topVC.navigationController?.pushViewController(VC, animated: true)
        }
        
        
        SoporteButton.M4EventUnavailable = false
    }
    @objc private func m4CloseAlert() {
        self.M4AlertViewHidden()
        closeButton.M4EventUnavailable = false
    }

}

class M4KFItemView: UIView {
    
    lazy var numberLabel: UILabel = {
        let label = UILabel()
        label.text = "880005566"
        label.textColor = COLOR_333333
        label.font = UIFont.systemFont(ofSize: 20, weight: .medium)
        return label
    }()
    
    lazy var m4waButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("", for: .normal)
        button.setImage(UIImage(named: "pop_icon_wa"), for: .normal)
        button.addTarget(self, action: #selector(M4JumpToWaClick), for: .touchUpInside)
        return button
    }()
    
    lazy var m4phoneButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("", for: .normal)
        button.setImage(UIImage(named: "pop_icon_telephone"), for: .normal)
        button.addTarget(self, action: #selector(M4JumpToCallClick), for: .touchUpInside)
        return button
    }()
    
    override init(frame: CGRect) {//28
        super.init(frame: .zero)
        self.backgroundColor = .white
        self.addSubview(numberLabel)
        numberLabel.snp.makeConstraints { make in
            make.left.centerY.equalToSuperview()
        }
        self.addSubview(m4phoneButton)
        m4phoneButton.snp.makeConstraints { make in
            make.right.centerY.equalToSuperview()
            make.width.height.equalTo(28)
        }
        self.addSubview(m4waButton)
        m4waButton.snp.makeConstraints { make in
            make.right.equalTo(m4phoneButton.snp.left).offset(-15)
            make.centerY.width.height.equalTo(m4phoneButton)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func M4JumpToWaClick() {
        if UIApplication.shared.canOpenURL(URL.init(string: "whatsapp://")!) {
            UIApplication.shared.open(URL.init(string: "https://wa.me/\(numberLabel.text ?? "")")!, options: [:], completionHandler: nil)
        } else {
            let str = "itms-apps://apps.apple.com/us/app/whatsapp-messenger/id310633997"
            guard let url = URL(string: str) else { return }
            let open = UIApplication.shared.canOpenURL(url)
            if open {
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(url, options: [:]) { _ in }
                } else {
                    UIApplication.shared.openURL(url)
                }
            }
        }
        print(numberLabel.text)
        m4waButton.M4EventUnavailable = false
    }
    
    @objc private func M4JumpToCallClick() {
        guard let url = URL(string: "tel://\(numberLabel.text ?? "")"),
              UIApplication.shared.canOpenURL(url) else {
            return
        }
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
           
        }

        print(numberLabel.text)
        m4phoneButton.M4EventUnavailable = false
    }
    
}
